package com.lzp.java.socket.tcp.demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * TCP服务端
 *
 * @author lzp
 * @date 2020/6/14
 */
public class FileServer {
    public static void main(String[] args) throws IOException {

        // 1. 创建ServerSocket，指定服务端端口号
        ServerSocket server = new ServerSocket(8889);
        while (true) {
            // 2. 监听客户端socket
            Socket socket = server.accept();
            // 3. 通过socket获取字节输入流
            InputStream is = socket.getInputStream();

            // 4. 判断目录是否存在
            File dir = new File("upload");
            if (!dir.exists()) {
                dir.mkdir();
            }

            // 5. 创建文件输出流，输出到目标位置
            String imgNam = "Img" + System.currentTimeMillis() + new Random().nextInt(9999) + ".jpg";
            FileOutputStream fos = new FileOutputStream(new File(dir, imgNam));
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = is.read(b)) != -1) {
                fos.write(b, 0, len);
            }

            // 6. 获取socket输出对象，回送信息给客户端
            OutputStream os = socket.getOutputStream();
            os.write("上传成功".getBytes());

            os.close();
            fos.close();
            is.close();
            socket.close();
        }

    }
}
